
var homePageId=sessionStorage.getItem("homePageId")
settingDetails()
function settingDetails() {
    $.ajax({
        type: "POST",
        url: root.brandWebsite.queryIndex,
        cache: false,  //禁用缓存
        dataType: "json",
        data: {
            "websiteId":homePageId,
        },
        success: function (data) {
            var datas=data.data
            $("#websiteColor").val(datas.brandWebsite.websiteColor)
            var websiteLabel=JSON.parse(datas.brandWebsite.websiteLabel)
            for(var i=0;i<websiteLabel.length;i++){
                $(".navigationName"+websiteLabel[i].labelId).html(websiteLabel[i].labelName)
            }
            $("#myImg").attr("src",datas.brandWebsite.websiteLogo)
            $("#myImg2").attr("src",datas.brandWebsite.websiteQrCode)
            $("#QRcode").val(datas.brandWebsite.websiteQrCodeName)
            $("#myImg3").attr("src",datas.brandWebsite.websiteSedQrCode)
            $("#QRcode2").val(datas.brandWebsite.websiteSedQrCodeName)
            $("#myImg4").attr("src",datas.brandWebsite.websiteIcon)
            $("#websitePhone").val(datas.brandWebsite.websitePhone)
            $("#websiteCaseNumber").val(datas.brandWebsite.websiteCaseNumber)
            var newlyAddedtable=""
            for (var k=0; k<datas.link.length;k++) {
            newlyAddedtable += '<div class="friend'+(k+1)+'" style="float:left;margin: 10px 0px 0px 210px;">' +
                '<label class="f-l lh-26  text-r"><span class="nameall">链接名称'+(k+1)+'：</span></label>' +
                '<input  style="width: 537px;" data-id="'+datas.link[k].id+'" id="linkName'+(k+1)+'" value="'+datas.link[k].friendLinkName+'"  class="input-text f-l w-250 radius linkName" maxlength="10" autocomplete="off">' +
                '<label class="f-l lh-26  text-r ml-10"><span>url配置：</span></label>' +
                '<input  style="width: 537px;" id="urlConfigure'+(k+1)+'" value="'+datas.link[k].friendLinkUrl+'"  class="input-text f-l w-250 radius urlConfigure" autocomplete="off" onkeyup="tipsall('+(k+1)+')"><span id="tips'+(k+1)+'" style="color: #dd0000;display: none" class="f-l lh-26  text-r ml-10">这是必填字段</span>' +
                '<a class="f-l lh-26  text-r ml-10" onclick="deletes(this,'+(k+1)+')">删除</a>' +
                '                    </div>'


            }

            $(".homepages").html(newlyAddedtable);
            //TDK
            $("#comfirmRemark").val(datas.tdk.pageTitle)
            $("#comfirmRemark2").val(datas.tdk.pageDescription)
            $("#comfirmRemark3").val(datas.tdk.pageKeywords)
            $("#TDKid").val(datas.tdk.id)

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    })
}

/*首页导航栏重命名修改*/
function modifyName(val) {
   $(".modifyName"+val).css("display","none");
   $(".preservation"+val).css("display","block");
   $(".preservationbutton"+val).css("display","block");
    $(".preservation"+val).val($(".navigationName"+val).html())

}
/*首页导航栏重命名保存*/
function preservation(val) {
    if($(".preservation"+val).val()==""){
        $.Huimodalalert('请填写信息',2000);
        return false;
    }
    $(".modifyName"+val).css("display","block");
    $(".navigationName"+val).html($(".preservation"+val).val())
    $(".preservation"+val).css("display","none");
    $(".preservationbutton"+val).css("display","none");
}

function addBtn(cen) {
    $(cen).prev().trigger('click');
}
//图片上传验证
var formData = new FormData();
// 提交上传图片
function getupfilerul(can,e){
    var formData = new FormData();
    formData.append('file',$(can)[0].files[0]);
    $.ajax({
        url: root.inter.imgUpload,
        cache: false,  //禁用缓存
        type: "POST",
        // 告诉jQuery不要去处理发送的数据
        processData : false,
        // 告诉jQuery不要去设置Content-Type请求头
        contentType : false,
        data: formData,
        success: function (data) {
            for(var i=0; i<data.length; i++){
                $(can).parent().parent().parent().find('img').attr("src", data[0].fullPath);
                $(can).parent().find('.fileupone').html('更换图片')
                $("#fileUpone").attr('type','text');
                $("#fileUpone").attr('type','file');
            }

        }
    })
}
// 上传图片返现
function putDataToPage(e,can,type) {
    //验证
    if(type==1){
        verificationPicFileType(can)
        verificationPicFileSize(can)
    }else if(type==2){
        verificationPicFileType(can)
        verificationPicFileSize(can)
    }else if(type==3){
        verificationPicFileType2(can)
        verificationPicFileSize(can)
    }

    for(var i = 0; i < e.target.files.length; i++) {
        var file = e.target.files.item(i);
        if(!(/^image\/.*$/i.test(file.type))) {
            continue; //不是图片 就跳出这一次循环
        }
        //实例化FileReader API
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            var data = e.target.result;
            //加载图片获取图片真实宽度和高度
            var img = new Image();
            img.src= data;
            img.onload = function(){
                var width = img.width;
                var height = img.height;
                console.log(height)
                if(type==1){
                    console.log("23830")
                     if (Number(width) == Number(238) && Number(height) == Number(30)){
                        getupfilerul(can,e)

                    }else {
                        $.Huimodalalert('请上传正确格式图片 ',2000);
                        file.value = "";
                        $("#fileUpone").attr('type','text');
                        $("#fileUpone").attr('type','file');
                        return;

                    }
                }else if(type==2){
                    console.log("80808008")
                    if (Number(width) == Number(80) && Number(height) == Number(80)){
                        getupfilerul(can,e)

                    }else {
                        $.Huimodalalert('请上传正确格式图片 ',2000);
                        file.value = "";
                        $("#fileUpone").attr('type','text');
                        $("#fileUpone").attr('type','file');
                        return;

                    }
                }else if(type==3){
                    console.log("3232")
                    if (Number(width) == Number(32) && Number(height) == Number(32)){
                        getupfilerul(can,e)

                    }else {
                        $.Huimodalalert('请上传正确格式图片 ',2000);
                        file.value = "";
                        $("#fileUpone").attr('type','text');
                        $("#fileUpone").attr('type','file');
                        return;

                    }
                }

                getupfilerul(can,e)

            };


        }
    }
    formData.append('file', $(can)[0].files[0]);
}
// 图片类型验证
function verificationPicFileType(file) {
    var flag=false;
    var fileTypes = [".jpg", ".png",".jpeg"];
    var filePath = file.value;
    //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
    if(filePath){
        var isNext = false;
        var fileEnd = filePath.substring(filePath.indexOf("."));
        for (var i = 0; i < fileTypes.length; i++) {
            if (fileTypes[i] == fileEnd) {
                isNext = true;
                flag= true;
                break;
            }
        }
        if (!isNext){
            $.Huimodalalert('请上传正确格式图片',2000);
            file.value = "";
            flag=false;
        }
    }
    return flag;
}
// 图片类型验证
function verificationPicFileType2(file) {
    var flag=false;
    var fileTypes = [".ico"];
    var filePath = file.value;
    //当括号里面的值为0、空字符、false 、null 、undefined的时候就相当于false
    if(filePath){
        var isNext = false;
        var fileEnd = filePath.substring(filePath.indexOf("."));
        for (var i = 0; i < fileTypes.length; i++) {
            if (fileTypes[i] == fileEnd) {
                isNext = true;
                flag= true;
                break;
            }
        }
        if (!isNext){
            $.Huimodalalert('请上传正确格式图片',2000);
            file.value = "";
            flag=false;
        }
    }
    return flag;
}
//图片大小验证
function verificationPicFileSize(file) {
    var flag=false;
    var fileSize = 0;
    var fileMaxSize = Number(1024);
    var filePath = file.value;
    if(filePath){
        fileSize =file.files[0].size;
        var size = fileSize / Number(1024);
        if (size > fileMaxSize) {
            $.Huimodalalert('上传图片过大，请压缩大小后再试',2000);
            file.value = "";
            flag=false;
        }else{
            flag=true;
        }
    }
    return flag;
}
//删除图片
function deletfilefns(e){
    edit_or_not=false
    $('#fileupones').html('图片上传')
    $(e).parent().parent().parent().find('img').attr('src','')
    $("#fileUpone").attr('type','text');
    $("#fileUpone").attr('type','file');

}

//首页友链接配置新增
var coner=30
function newlyAdded() {
    var homepagelength=$('.homepages div').length+1
    var newlyAddedtable=""
    newlyAddedtable += '<div class="friend'+homepagelength+'" style="float:left;margin: 10px 0px 0px 210px;">' +
        '<label class="f-l lh-26  text-r"><span class="nameall">链接名称'+homepagelength+'：</span></label>' +
        '<input  style="width: 537px;" data-id="0" id="linkName'+homepagelength+'"  class="input-text f-l w-250 radius linkName" maxlength="10" autocomplete="off">' +
        '<label class="f-l lh-26  text-r ml-10"><span>url配置：</span></label>' +
        '<input  style="width: 537px;" id="urlConfigure'+homepagelength+'"  class="input-text f-l w-250 radius urlConfigure" autocomplete="off" onkeyup="tipsall('+homepagelength+')"><span id="tips'+homepagelength+'" style="color: #dd0000;display: none" class="f-l lh-26  text-r ml-10">这是必填字段</span>' +
        '<a class="f-l lh-26  text-r ml-10" onclick="deletes(this,'+homepagelength+')">删除</a>' +
        '                    </div>'
    if($('.homepages div').length<coner){
        $(".homepages").append(newlyAddedtable);
    }else {
        layer.msg('配置数量超上限', {icon: 5, time: 1000});

    }
}
//首页友链接配置url标红提示
function tipsall(val) {
    $("#tips"+val).css({
        display:"none"
    });
}
//删除首页友链接配置
function deletes(obj,val) {
    var cu = layer.confirm('<span>确定删除吗？</span>', {title:'提示',btn: ['确认', '取消']}, function(index){
        $(obj).parent("div").remove();
        numCheck()
        layer.close(cu);
    },function(){
        layer.close(cu);

    });

}
function numCheck(){
    var num = $('.homepages div').length;     //获取行数
    for (var i = 0; i <= num; i++) {         //进行循环
        $('.homepages div .nameall').eq(i).html('链接名称'+(i+1)+'：');
    };
}

//保存
$("#form-memberadd").validate({
    rules: {

        websiteColor:{
            required: true,//是否是必填项
            },
        //首页导航栏重命名
        rename1:{
            required: true,//是否是必填项
        },
        rename2:{
            required: true,//是否是必填项
        },
        rename3:{
            required: true,//是否是必填项
        },
        rename4:{
            required: true,//是否是必填项
        },
        rename5:{
            required: true,//是否是必填项
        },
        rename6:{
            required: true,//是否是必填项
        },
        rename7:{
            required: true,//是否是必填项
        },

        contactNumber:{
            required: true,//首页联系电话配置
        },
        //TDK
        remarkVal1:{
            required: true,//是否是必填项
        },
        remarkVal2:{
            required: true,//是否是必填项
        },
        remarkVal3:{
            required: true,//是否是必填项
        },

    },
    submitHandler:function(form) {
        adddatas()
    }





})
function adddatas() {
    //首页友链接配置url效验
    var imgs = new Array();
    var liksdatas={}
    var liksdataarr=[]
        var divdata=$('.homepages div')
    for (var i = 0; i < divdata.length; i++) {
        console.log()
        liksdatas={
            "id":$("#linkName" + (i+1)).attr("data-id"),
            "websiteId":homePageId,
            "friendLinkName":$(divdata[i]).find(".linkName").val(),
            "friendLinkUrl":$(divdata[i]).find(".urlConfigure").val(),
            "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name
        }
        if($(divdata[i]).find(".linkName").val()==""&&$(divdata[i]).find(".urlConfigure").val()!=""){
            $.Huimodalalert('请完善名称或URL后保存',2000);
            return false;
        }
        if($(divdata[i]).find(".linkName").val()!="" && $(divdata[i]).find(".urlConfigure").val()==""){
            $.Huimodalalert('请完善名称或URL后保存',2000);
            return false;
        }
        if($(divdata[i]).find(".linkName").val()!=""&&$(divdata[i]).find(".urlConfigure").val()!=""){
            liksdataarr.push(liksdatas)
        }

    }

            if($("#myImg").attr("src")==""){
                $.Huimodalalert('请上传首页logo',2000);
                return false;
            }

    //图片名称效验
    if ($("#myImg2").attr("src") != "" && $("#QRcode").val() == "") {
        $("#imgts").css({
            display: "block"
        });
        $.Huimodalalert('请完善必填信息',2000);
        return false
    } else {
        $("#imgts").css({
            display: "none"
        });
    }

    if ($("#myImg2").attr("src") == "" && $("#QRcode").val() != "") {
        $.Huimodalalert('请完善二维码配置',2000);
        return false;
    }
    if ($("#myImg3").attr("src") != "" && $("#QRcode2").val() == "") {
        $("#imgts2").css({
            display: "block"
        });
        $.Huimodalalert('请完善必填信息',2000);
        return false
    } else {
        $("#imgts2").css({
            display: "none"
        });
    }
    if ($("#myImg3").attr("src") == "" && $("#QRcode").val() != "") {
        $.Huimodalalert('请完善二维码配置',2000);
        return false;
    }

    if($("#myImg4").attr("src")==""){
        $.Huimodalalert('请上传链接logo',2000);
        return false;
    }
    var websiteLabelall={}
    var websiteLabelarr=[]
    for (var i = 1; i < 7; i++) {
        websiteLabelall = {
            "labelId": i,
            "labelName": $(".navigationName" + i).html()
        }
        websiteLabelarr.push(websiteLabelall)
    }


    var brandWebsites={
        "id":homePageId,
        "websiteName":"",
        "websiteUrl":"",
        "websiteColor":$("#websiteColor").val(),
        "websiteIcon":$("#myImg4").attr("src"),
        "websiteLabel":JSON.stringify(websiteLabelarr),
        "websiteLogo":$("#myImg").attr("src"),
        "websiteQrCode":$("#myImg2").attr("src"),
        "websiteQrCodeName": $("#QRcode").val(),
        "websiteSedQrCode":$("#myImg3").attr("src"),
        "websiteSedQrCodeName":$("#QRcode2").val(),
        "websitePhone":$("#websitePhone").val(),
        "websiteCaseNumber":$("#websiteCaseNumber").val(),
        "websiteContactDetails":"",
        "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
    }


    var TDKdatas={
        "id": $("#TDKid").val(),
        "msgId":0,
        "websiteId":homePageId,
        "pageType":1,
        "pageTitle": $("#comfirmRemark").val(),
        "pageDescription": $("#comfirmRemark2").val(),
        "pageKeywords": $("#comfirmRemark3").val(),
        "createUser":JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,
    }

    $.ajax({
        type: "POST",
        url: root.brandWebsite.updateIndex,
        cache: false,  //禁用缓存
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            brandWebsite:brandWebsites,
            link: liksdataarr,
            tdk: TDKdatas
        }),
        success: function (data) {
            if(data.errorCode==0){
                layer.msg("保存成功",{icon: 6,time:2000},function () {
                    setTimeout(function () {
                        window.parent.homePagequerys();
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    })
                });

            }else {
                $.Huimodalalert(data.msg,2000);
            }

        },
        error: function () {
            $.Huimodalalert('失败！',2000);
        }
    });
}

